package com.jinlejia.erp.ui.new_house.house;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.CitysBean;
import com.jinlejia.erp.databinding.ActivityCitySelectBinding;
import com.jinlejia.erp.ui.new_house.adapter.CitySelectAdapter;
import com.jinlejia.erp.ui.new_house.adapter.HorizontalCityAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.PinyinCityComparator;
import com.jinlejia.erp.utils.SharePTool;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class CitySelectActivity extends AppCompatActivity {

    CitySelectAdapter adapter;
    private List<CitysBean> SourceDateList = new ArrayList<>();
    private ArrayList<String> first = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinCityComparator pinyinCityComparator;
    private ActivityCitySelectBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_city_select);
        binding.idBack.setOnClickListener(v -> onViewClicked());
        initView();
        getData();
    }

    public void onViewClicked() {
        finish();
    }

    private void initView() {
        pinyinCityComparator = new PinyinCityComparator();
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setHasFixedSize(true);

        List<String> historyCity = SharePTool.getHistoryCity(this);
        if (historyCity.size() > 0) {
            binding.history.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.history.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        }
        HorizontalCityAdapter cityAdapter = new HorizontalCityAdapter(this, historyCity);
        recyclerView.setAdapter(cityAdapter);


        //设置右侧触摸监听
        binding.sideBar.setOnTouchingLetterChangedListener(s -> {
            //该字母首次出现的位置
            if (adapter != null) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    binding.idCityList.setSelection(position);
                }
            }
            CustomToast.showToast(CitySelectActivity.this, s, 1000);
        });
        cityAdapter.setOnItemClickLitener((city, position) -> {
            Intent intent = new Intent();
            intent.putExtra("city", city);
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    private void getData(){
        OkHttpUtils.get().url(ApiConfig.CITY_LIST)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if(DataFilter.filter(CitySelectActivity.this,response)){
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            ArrayList<CitysBean> CityList = new ArrayList<CitysBean>();
                            Iterator<String> iterator = object.keySet().iterator();
                            while (iterator.hasNext()){
                                String key =  iterator.next();
                                first.add(key);
                                ArrayList<String> list = JSON.parseObject(object.getJSONArray(key).toString(),new TypeReference<ArrayList<String>>(){});
                                for (int i = 0; i < list.size(); i++) {
                                    CitysBean citysBean = new CitysBean();
                                    citysBean.setCityName(list.get(i));
                                    citysBean.setCityPacket(key.toUpperCase());
                                    CityList.add(citysBean);
                                }
                            }
                            SourceDateList = CityList;
                            // 根据a-z进行排序源数据
                            Collections.sort(SourceDateList, pinyinCityComparator);
                            binding.sideBar.setList(first);
                            adapter = new CitySelectAdapter(CitySelectActivity.this,SourceDateList);
                            binding.idCityList.setAdapter(adapter);

                            adapter.OnItemListener(city -> {
                                SharePTool.saveHistoryCity(CitySelectActivity.this,city);
                                Intent intent = new Intent();
                                intent.putExtra("city", city);
                                setResult(RESULT_OK, intent);
                                finish();
                            });
                        }
                    }
                });
    }

}
